package com.aliyun.messagemgt.application.service.Impl;

import com.aliyun.messagemgt.application.service.RealTimeCountService;
import com.aliyun.messagemgt.application.service.mq.MsgMiddleResult;
import com.aliyun.messagemgt.application.service.mq.MsgRecordVO;
import com.aliyun.messagemgt.util.redis.Redis;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author
 * @date
 */
@Service
public class RealTimeCountServiceImpl implements RealTimeCountService {

	/**
	 * redis消息保存键前缀
	 */
	private static final String MESSAGE_SEND = "messageSend";

	/**
	 * 失效时间24小时
	 */
	private static final int EXPIRETIME = 86400;

	@Override
	public void add(List<MsgRecordVO> msgRecordVOs) {
		for (MsgRecordVO msgRecordVO : msgRecordVOs) {
			// 部门编码
			String deptCode = msgRecordVO.getOwnerDept();
			String msgSourceId = msgRecordVO.getMsgSourceId();
			// 获取key
			StringBuilder sb = new StringBuilder(MESSAGE_SEND);
			String date = Redis.generateDate();
			sb.append(".").append(date).append(".").append(msgSourceId);
			String key = sb.toString();
			// 获取总数量
			int num = doTotal(msgRecordVO);
			// 获取该部门一共有多少条消息多少条
			String numOld = doCountByDeptCode(key, deptCode, num);
			// 改变部门条数
			Redis.hset(key, deptCode, numOld, EXPIRETIME);
			// 获取总条数
			StringBuilder sb1 = new StringBuilder(MESSAGE_SEND);
			String keyTotal = sb1.append(".").append(date).append(".").append("total").toString();
			String numOldTotal = doCountByDeptCode(keyTotal, deptCode, num);
			// 改变部门条数
			Redis.hset(keyTotal, deptCode, numOld, EXPIRETIME);

		}

	}

	/**
	 * 获取该部门条数，并和这次消息条数求和
	 * 
	 * @param key
	 * @param deptCode
	 * @param num
	 * @return
	 */
	private String doCountByDeptCode(String key, String deptCode, int num) {
		String numOld = Redis.hmget(key, deptCode);
		if (StringUtils.isBlank(numOld)) {
			numOld = String.valueOf(num);
		} else {
			numOld = String.valueOf((num + Integer.valueOf(numOld)));
		}
		return numOld;
	}

	/**
	 * 这次消息发送成功总条数
	 * 
	 * @param msgRecordVO
	 * @return
	 */
	private int doTotal(MsgRecordVO msgRecordVO) {
		int num = 0;
		// 推送结果
		List<MsgMiddleResult> listResult = msgRecordVO.getResults();
		if (!CollectionUtils.isEmpty(listResult)) {
			for (MsgMiddleResult msgMiddleResult : listResult) {
				if (msgMiddleResult.getPushResultCode() == 1) {
					num += msgMiddleResult.getReceivers().size();
				}
			}
		}
		// 重发推送结果
		List<MsgMiddleResult> listReSendResult = msgRecordVO.getResendesults();
		if (!CollectionUtils.isEmpty(listReSendResult)) {
			for (MsgMiddleResult msgMiddleResult : listReSendResult) {
				if (msgMiddleResult.getPushResultCode() == 1) {
					num += msgMiddleResult.getReceivers().size();
				}
			}
		}
		return num;
	}
}
